{extend name="public:base"}
{block name='css'}
{/block}

{block name='body'}
<div class="view view-main white-navbar white-toolbar">
    <div data-name="home" class="page">

        <div class="navbar">
            <div class="navbar-inner">
                <div class="left"><a href="javascript:history.back();" class="external"><i class="iconfont icon-fanhui"></i></a></div>
                <div class="center"><span>结算</span></div>
                <div class="right"></div>
            </div>
        </div>

        <div class="page-content padding-bottom50">

            <div class="jiesuan">

                <div class="adre" {notempty name='address_list'}style="display:none;"{/notempty}>
                    <div class="noad" onclick="app.popup.open('.addAddress' , true);">
                        <i class="iconfont icon-tianjia"></i><br />添加收货地址
                    </div>
                </div>

                <div class="adre" {empty name='address_list'}style="display:none;"{/empty}>
                    <div class="yead" onclick="app.popup.open('.addressList' , true);">
                        <div class="ico"><i class="iconfont icon-dizhi"></i></div>
                        <div class="z">
                            <p class="p1 js-name">{$address_list[0]['name']|default=''}&nbsp;&nbsp;&nbsp;&nbsp;{$address_list[0]['tel']|default=''}&nbsp;&nbsp;&nbsp;{if condition="isset($address_list[0]['is_default']) && $address_list[0]['is_default'] eq 1"}<i>默认</i>{/if}</p>
                            <p class="p2 js-addr">{$address_list[0]['sca_name']|default=''} {$address_list[0]['address']|default=''}</p>
                        </div>
                        <div class="y"><i class="iconfont icon-jiantou"></i></div>
                    </div>
                </div>

                <div class="goods">
                    {volist name='goods' id='vo'}
                    <div class="mt">
                        <img src="{$vo.img}" alt="" />
                        <div class="y">
                            <p class="p1">{$vo.title}</p>
                            <!-- <p class="p3">{$vo.spec|default=''}</p> -->
                            <p class="p2"><span>￥{$vo.unit_price}</span>x {$vo.num}</p>
                        </div>
                    </div>
                    {/volist}
                </div>
                <form id="js-place">
                    <input type="hidden" name="address_id" value="{$address_list[0]['id']|default=0}"/>
                    <div class="list inline-labels no-hairlines-md" style="margin:0px;">
                        <ul>
                            <li class="item-content item-input">
                                <div class="item-inner">
                                    <div class="item-title item-label" style="width:60px;">备注</div>
                                    <div class="item-input-wrap">
                                        <textarea class="resizable" name="remark" placeholder="选填，请输入备注内容..."></textarea>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </div>

                <div class="jie">
                    <p class="p1">
                        <span>余额支付<i>(￥{$_user.balance})</i></span>
                        <label class="toggle toggle-init color-green">
                            <input type="radio" value="balance" name="pay_way"  checked>
                            <!-- <span class="toggle-icon"></span> -->
                        </label>
                    </p>
                    <p class="p1">
                        <span>微信支付<i></i></span>
                        <label class="toggle toggle-init color-green">
                            <input type="radio" value="wechat" name="pay_way">
                            <!-- <span class="toggle-icon"></span> -->
                        </label>
                    </p>
                </div>
                <!-- <div>
                    <span>自动复购</span>
                    <input type="radio" value="1" name="is_again_buy"  >

                </div> -->
                </form>

            </div>
            <div id="allmap" style="display: none;"></div>
        </div>

        <div class="toolbar">
            <div class="topay">
                <div class="z">应付金额：<span class="js-order-amount">￥{$total}</span></div>
                <div class="y submit">去支付</div>
            </div>
        </div>
        
    </div>
    <!-- onclick="toPay();" -->
</div>
<!-- &lt;!&ndash; 支付弹窗 &ndash;&gt; -->

<!--添加收货地址-->
<div class="popup addAddress">
    <div class="view white-navbar white-page white-toolbar">
        <div class="page">
            <div class="navbar">
                <div class="navbar-inner">
                    <div class="left"><a href="javascript:app.popup.close('.addAddress',true);" class="external"><i class="iconfont icon-guanbi"></i></a></div>
                    <div class="center"><span>添加收货地址</span></div>
                </div>
            </div>
            <div class="page-content">
                <form name="form" action="" id="addAddress" method="post" onsubmit="return false;">
                    <div class="list inline-labels no-hairlines-md addlis">
                        <ul>
                            <li class="item-content item-input">
                                <div class="item-inner">
                                    <div class="item-title item-label">收货人</div>
                                    <div class="item-input-wrap">
                                        <input type="text" name="name" placeholder="请输入收货人姓名">
                                        <span class="input-clear-button"></span>
                                    </div>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-inner">
                                    <div class="item-title item-label">联系电话</div>
                                    <div class="item-input-wrap">
                                        <input type="number" name="tel" placeholder="请输入联系电话">
                                        <span class="input-clear-button"></span>
                                    </div>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-inner">
                                    <div class="item-title item-label">所在地区</div>
                                    <div class="item-input-wrap js-region" style="display:flex;">
                                        <select name="sheng_id" onchange="getRegion(this, 1)">
                                            <option value="1">请选择省</option>
                                        </select>
                                        <select name="city_id" onchange="getRegion(this, 2)">
                                            <option value="1">请选择市</option>
                                        </select>
                                        <select name="area_id" onchange="getRegion(this, 3)">
                                            <option value="1">请选择区</option>
                                        </select>
                                    </div>
                                </div>
                            </li>
                            <input type="hidden" name="sca_name"/>
                            <li class="item-content item-input">
                                <div class="item-inner">
                                    <div class="item-title item-label">详细地址</div>
                                    <div class="item-input-wrap">
                                        <input type="text" name="address" placeholder="请输入详细地址">
                                        <span class="input-clear-button"></span>
                                    </div>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-inner">
                                    <div class="item-title item-label">默认地址</div>
                                    <div class="item-input-wrap">
                                        <label class="toggle toggle-init color-green">
                                            <input type="checkbox" name="is_default" value="1" checked="checked" >
                                            <span class="toggle-icon"></span>
                                        </label>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </div>
                    <div class="block">
                        <p class="row segmented-round">
                            <button class="col button button-big button-fill button-round" style="background:#515262;">保存</button>
                        </p>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!--切换收货地址-->
<div class="popup addressList">
    <div class="view white-navbar white-page white-toolbar">
        <div class="page">
            <div class="navbar">
                <div class="navbar-inner">
                    <div class="left"><a href="javascript:app.popup.close('.addressList',true);" class="external"><i class="iconfont icon-guanbi"></i></a></div>
                    <div class="title"><span>选择收货地址</span></div>
                    <div class="right">
                        <a href="javascript:app.popup.close('.addressList',true);app.popup.open('.addAddress' , true);" class="external addshouhuo">添加 <i class="iconfont icon-tianjia"></i></a>
                    </div>
                </div>
            </div>

            <div class="page-content">
                <div class="addlist" >
                </div>
            </div>
        </div>
    </div>
</div>
<div class="popup addressList">
    <div class="view white-navbar white-page white-toolbar">
        <div class="page">
            <div class="navbar">
                <div class="navbar-inner">
                    <div class="left"><a href="javascript:app.popup.close('.addressList',true);" class="external"><i class="iconfont icon-guanbi"></i></a></div>
                    <div class="title"><span>选择收货地址</span></div>
                    <div class="right">
                        <a href="javascript:app.popup.close('.addressList',true);app.popup.open('.addAddress' , true);" class="external addshouhuo">添加 <i class="iconfont icon-tianjia"></i></a>
                    </div>
                </div>
            </div>

            <div class="page-content">
                <div class="addlist" >
                </div>
            </div>
        </div>
    </div>
</div>
<!-- &lt;!&ndash; 支付弹窗 &ndash;&gt; -->

    <div class="view white-navbar white-page white-toolbar">
        <div class="payAlert">
            <form action="">
                <ul class="payAlertHeader">
                    <li><i class="iconfont icon-fanhui colsePay"></i></li>
                    <li>请输入支付密码</li>
                    <li></li>
                </ul>
                <input class="pswInp" type="password" id="pay_password" placeholder="请输入支付密码">
                <!-- <a href="" charset="forgetMM">忘记密码？</a> -->
                <a href="javascript:;" class="payBtn">确认支付</a>
            </form>
        </div>
        <div class="productDetailArtBg"></div>

    </div>

{/block}

{block name="js"}
<!-- <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=UQp3MkwNdYHMuDaZ28dIm84c3GCPnmkK"></script> -->
<script>
    var params;
    var address = "{$address_list[0]['sca_name']|default=''} {$address_list[0]['address']|default=''}";
    // var map = new BMap.Map("allmap");
    // 创建地址解析器实例
    // var myGeo = new BMap.Geocoder();
    // calAddr(address);
    // 将地址解析结果显示在地图上,并调整地图视野
    // function calAddr(address) {
    //     myGeo.getPoint(address, function (point) {
    //         if (point) {
    //             map.centerAndZoom(point, 16);
    //             map.addOverlay(new BMap.Marker(point));

    //             params = {
    //                 lng: point.lng,
    //                 lat: point.lat,
    //                 min_km: '{$min_km|default=0}'
    //             };
    //             $.post("{:url('cart/checkOverrun')}", params, function (data) {
    //                 if (data.status == 'y') {

    //                 } else {
    //                     messageToast(data.info);
    //                 }
    //             }, 'json');
    //             $('.lng').val(point.lng);
    //             $('.lat').val(point.lat);

    //         } else {
    //             params = {
    //                 address: address,
    //                 min_km: '{$min_km|default=0}'
    //             };
    //             $.post("{:url('cart/checkOverrun')}", params, function (data) {
    //                 if (data.status == 'y') {

    //                 } else {
    //                     messageToast(data.info);
    //                 }
    //             }, 'json');
    //         }
    //     }, "重庆市");
    // }
</script>
<script type="text/javascript">
    /*{notempty name='address_list'}*/
    var address_list = {$address_list|json_encode=###,JSON_UNESCAPED_UNICODE};
    /*{else/}*/
    var address_list = [];
    /*{/notempty}*/
    function setAddr(addr) {
        $('.js-name').html(addr.name + '&nbsp;&nbsp;&nbsp;&nbsp;' + addr.tel + '&nbsp;&nbsp;&nbsp;&nbsp;' + (addr.is_default == 1 ? '<i>默认</i>' : ''));
        $('.js-addr').text(addr.sca_name + ' ' + addr.address);
        $('input[name=address_id]').val(addr.id);
        // calAddr(addr.sca_name + ' ' + addr.address);
        $('.adre').eq(0).hide();
        $('.adre').eq(1).show();
    }
    function selectThis(index) {
        setAddr(address_list[index]);
        // calAddr(address_list[index].sca_name + ' ' + address_list[index].address);
        $('.icon-guanbi').click();
    }
    function setAddrList() {
        var str = '';
        $.each(address_list, function(i,n){
            str += '<div class="li" onclick="selectThis('+i+')">\n' +
                '    <div class="m">\n' +
                '        <div class="z">\n' +
                '            <p class="p1">'+n.name+'&nbsp;&nbsp;&nbsp;&nbsp;'+n.tel+'&nbsp;&nbsp;&nbsp;'+(n.is_default == 1 ? '<i>默认</i>' : '')+'</p>\n' +
                '            <p class="p2">'+n.sca_name+' '+n.address+'</p>\n' +
                '        </div>\n' +
                '        <div class="y"><i class="iconfont icon-jiantou"></i></div>\n' +
                '    </div>\n' +
                '</div>'
        });
        $('.addlist').html(str);
    }
    $(function(){
        getRegion(0, 0);
        setAddrList();
        var ajaxOn = false;
        $("#addAddress").validate({
            rules: {
                name: "required" ,
                tel: "required" ,
                sheng_id: "required" ,
                city_id: "required" ,
                area_id: "required" ,
                address: "required"
            },
            messages: {
                name: '请输入收货人姓名',
                tel: '请输入联系电话',
                sheng_id: '请选择省',
                city_id: '请选择市',
                area_id: '请选择区',
                address: '请输入详细地址'
            },
            showErrors: function (errorMap, errorList) {
                var msg = "";
                $.each(errorList, function (i, v) {
                    var toastCenter = app.toast.create({
                        text: v.message,
                        position: 'center',
                        closeTimeout: 2000
                    });
                    toastCenter.open();
                    return false;
                });
            },
            onfocusout: false,
            onsubmit : true ,
            onkeyup : false ,
            onclick : false ,
            focusInvalid:false,
            submitHandler:function(form){
                if (ajaxOn) {
                    return false;
                }
                ajaxOn = true;
                $.post("{:url('user/save_address')}", $('#addAddress').serialize(), function(data){
                    ajaxOn = false;
                    if (data.status == 'y') {
                       
                        $('.icon-guanbi').click();
                        setAddr(data.data);
                        if (data.data.is_default == 1) {
                            $.each(address_list, function(i,n){
                                n.is_default = 0;
                            });
                        }
                        address_list.push(data.data);
                        $('.input-clear-button').click();
                        // $("select[name=sheng_id] option").eq(0).prop('selected', true);
                        // $("select[name=sheng_id]").change();
                        setAddrList();
                    } else {
                        app.dialog.alert(data.info);
                    }
                }, 'json');
                return false ;
            }
        });
    });
    function changePay(self) {
        if ($(self).is(':checked')) {
            $('.js-order-amount').text('￥{php}echo amountFormat($order_amount - $balance < 0 ? 0 : $order_amount - $balance);{/php}');
        } else {
            $('.js-order-amount').text('￥{$order_amount}');
        }
    }
   
    function toPay() {
        if (ajaxOn) {
            return false;
        }
        app.dialog.confirm("您确定要前往支付吗？", function(){
            ajaxOn = true;
            $.post("{:url('/payment')}", $('#js-place').serialize(), function(data){
                // messageToast(data.info);
                if(data.code ==1){
                    location.href='/group_info';
                    //订单创建成功 跳转
                    // setTimeout(function () {
                    //     self.location = data.data;
                    // }, 1000);
                }else if(data.code==2){
                    //微信支付
                    layer.msg('正在拉取支付...', {time: 1000}, function () {
                        callpay(data.result.appId, data.result.nonceStr, data.result.package, data.result.paySign, data.result.signType, data.result.timeStamp, data.result.timestamp);
                    });
                }else{
                    layer.msg(data.msg);
                }
                ajaxOn = false;
            }, 'json');
        });
    }
    function jsApiCall(appId, nonceStr, package, paySign, signType, timeStamp, timestamp) {
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
                "appId": appId,
                "nonceStr": nonceStr,
                "package": package,
                "paySign": paySign,
                "signType": signType,
                "timeStamp": timeStamp,
            },
            function (res) {
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                    location.href = '/group_info';
                } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                    location.reload();
                }
            }
        );
    }
    function callpay(appId, nonceStr, package, paySign, signType, timeStamp, timestamp) {
        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', jsApiCall(appId, nonceStr, package, paySign, signType, timeStamp, timestamp), false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', jsApiCall(appId, nonceStr, package, paySign, signType, timeStamp, timestamp));
                document.attachEvent('onWeixinJSBridgeReady', jsApiCall(appId, nonceStr, package, paySign, signType, timeStamp, timestamp));
            }
        } else {
            jsApiCall(appId, nonceStr, package, paySign, signType, timeStamp, timestamp);
        }
    }
 
</script>
<script>
    iss=true;
    var ajaxOn = false;
    $(".submit").click(function () {
    if (iss !== true) return false;
    $('.payAlert').fadeIn();
    $('.productDetailArtBg').fadeIn();
    });
    $('.productDetailArtBg, .colsePay ').click(function () {
        $('.productDetailArtBg').fadeOut();
        $('.payAlert').fadeOut();
        $('.pswInp').val('');
    })
    $(".payBtn").click(function () {
        if (iss !== true) return false;
        app.dialog.confirm("您确定要前往支付吗？", function(){
            iss = false;
            let pay_way = $("input[type='radio']:checked").val();
            let pay_password = $('.pswInp').val();
            if (!pay_way) {
                layer.msg('请选择支付方式');
                iss = true;
                return false;
            }
            if (!pay_password) {
                layer.msg('请输入支付密码');
                iss = true;
                return false;
            }
            let load = layer.load(2);
            $.post("{:url('/payment')}", $('#js-place').serialize()+'&'+$.param({'pay_password':pay_password}), function(data){
                // messageToast(data.info);
                if(data.code ==1){
                    location.href='/group_info';
                    //订单创建成功 跳转
                    // setTimeout(function () {
                    //     self.location = data.data;
                    // }, 1000);
                }else if(data.code==2){
                    //微信支付
                    layer.msg('正在拉取支付...', {time: 1000}, function () {
                        callpay(data.result.appId, data.result.nonceStr, data.result.package, data.result.paySign, data.result.signType, data.result.timeStamp, data.result.timestamp);
                    });
                }else{
                    layer.msg(data.msg);
                    layer.close(load);

                    iss = true;

                }
            }, 'json');
        });
    })
    </script>
{/block}